class Web3Manager extends Laya.EventDispatcher{

    /**
     * 帐号变更
     */
    public static ACCOUNT_CHANGE:string = "ACCOUNT_CHANGE";

    /**
     * 空账号
     */
    public static EMPTY_ACCOUNT:string = "0x0000000000000000000000000000000000000000";

    private static _instance:Web3Manager;//单例

    public static defaultAccount:string = "";//帐号
    public static nowNet:string;//当前线路
    private static _web3:any;//web3对象
    private static _tokenContract:any;//合约

    /**
     * 获取单例
     */
    public static getInstance():Web3Manager{
        if(Web3Manager._instance == null){
            Web3Manager._instance = new Web3Manager();
        }
        return Web3Manager._instance;
    }

    /**
     * 初始化
     */
    public init():void{
        Web3Manager._web3 = window["web3"];
        if(Web3Manager._web3 == null){
            Alert.getInstance().showMsg = LangUtils.getText(20);
            Alert.getInstance().open();
            return;
        }
        //线路
        Global.NEED_NET = MateMaskType.MAIN_NET;
        //Abi
        Global.ABI = Laya.loader.getRes(ResUtils.getLoadUrl("res/abi.json"));
        //定时器 检测线路 和帐号
        Laya.timer.loop(100,Web3Manager,Web3Manager.checkNetWork);
    }

    /**
     * 检测帐号是否为空
     */
    public static checkDefAccountIsEmpty():boolean{
        return Web3Manager.defaultAccount == null || Web3Manager.defaultAccount == "";
    }

    /**
     * 检测线路
     */
    private static checkNetWork=()=>{
        //检测网络
        Web3Manager._web3.version.getNetwork((err,newNet)=>{
            //刷新获取帐号
            Web3Manager.updateMeAccount();
            //检测 线路 是否有变更
            if(Web3Manager.nowNet == newNet){
                return;
            }
            Web3Manager.nowNet = newNet;
            //检测线路 是否是需要的线路
            if(newNet != Global.NEED_NET){
                Web3Manager._tokenContract = null;
                var content:string = LangUtils.getText(19);
                content = content.replace("[2]",MateMaskType.getNetName(Global.NEED_NET));
                content = content.replace("[1]",MateMaskType.getNowNetName());
                Alert.getInstance().showMsg = content;
                Alert.getInstance().open();
            }else if(Web3Manager._tokenContract == null){
                //合约token
                Web3Manager._tokenContract = Web3Manager._web3.eth.contract(Global.ABI).at(Global.Address);
            }
        });
    }

    //刷新获取帐号
    private static updateMeAccount():void{
        var nowAccount:string = Web3Manager._web3.eth.accounts[0];
        if(Web3Manager.defaultAccount != nowAccount){
            Web3Manager.defaultAccount = nowAccount;
            Web3Manager._instance.event(Web3Manager.ACCOUNT_CHANGE);
        }else{
            Web3Manager.defaultAccount = nowAccount;
        }
        Web3Manager._web3.eth.defaultAccount = Web3Manager.defaultAccount;
    }

    /**
     * 执行合约
     */
    public static execContract(execFun:Function,args:Array<any>,callFun:Function):void{
        if(Web3Manager._tokenContract == null){
            return;
        }
        var promise = new Promise(function(resolve,reject){
            execFun(args,resolve,reject);
        });
        promise.then(function(value){
            callFun(value,"suc");
        }).catch(function(error){
            callFun(error,"fal");
        });
    }

    /**
     * 请求购买
     */
    public static reqBuy(args:Array<any>,resolve:any,reject:any):void{
        var param:Object = {value:Web3Manager._web3.toWei(Number(0.2),'ether'),gas:220000,gasPrice:1000000000*100};
        Web3Manager._tokenContract.buyCountry(args[0],param,(err,result)=>(err?reject(err):resolve(result)));
    }

    /**
     * 请求土地归属信息
     */
    public static reqOwnInfo(args:Array<any>,resolve:any,reject:any):void{
        var param:Object = {};
        Web3Manager._tokenContract.countryOwnersOf(param,(err,result)=>(err?reject(err):resolve(result)));
    }

    /**
     * 请求上一局的胜利者
     */
    public static reqLastWin(args:Array<any>,resolve:any,reject:any):void{
        var param:Object = {};
        Web3Manager._tokenContract.winAddressOf(param,(err,result)=>(err?reject(err):resolve(result)));
    }

    /**
     * 请求当前局数
     */
    public static reqCount(args:Array<any>,resolve:any,reject:any):void{
        var param:Object = {};
        Web3Manager._tokenContract.battleCountOf(param,(err,result)=>(err?reject(err):resolve(result)));
    }

    /**
     * 请求历史记录信息
     */
    public static reqHistory(args:Array<any>,resolve:any,reject:any):void{
        var param:Object = {};
        Web3Manager._tokenContract.getHistory(args[0],args[1],param,(err,result)=>(err?reject(err):resolve(result)));
    }
}

